<?php
namespace Peas\Utils;

/**
 * Peas Framework
 *
 * 敏感词过滤
 *
 * @author  Hongzan Zhang <zhanghongzan@163.com>
 * @version $Id$
 */
class CensorUtils
{
    /**
     * 敏感词检测
     *
     * @param  string $words 待检测内容
     * @return 没有敏感词则返回false，有则返回第一个匹配到的敏感词
     */
    public static function check($words) {
        $len = mb_strlen($words, 'utf-8');
        if ($len <= 0) {
            return false;
        }
        $checked = [];
        $forbidden = unserialize(file_get_contents(dirname(dirname(__DIR__)) . '/resource/data/censor.txt'));
        for ($i = 0; $i < $len; $i ++) {
            $key = mb_substr($words, $i, 1, 'utf-8');
            if (in_array($key, $checked)) {
                continue;
            }
            if (key_exists($key, $forbidden)) {
                $arr = $forbidden[$key];
                foreach ($arr as $str) {
                    if (strpos($words, $str, $i) !== false) {
                        return $str;
                    }
                }
            }
            $checked[] = $key;
        }
        return false;
    }
}
